using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Se.Framework.Common;
using Se.Framework.Common.Extentions;
using Se.Framework.Web.Mvc.GenericCrud.Attributes;

namespace Se.Framework.Web.Mvc.GenericCrud
{
    public class GenericCrudColumnData : IGenericCrudColumnData
    {
        public string Name { get; set; }

        public Type Type { get; set; }

        public Type SearchType { get; set; }

        public DisplayAttribute DisplayAttr { get; set; }

        public GenericCrudRenderMode RenderMode { get; set; }

        public bool Sortable { get; set; }

        public bool Editable { get; set; }

        public bool Required { get; set; }

        public GenericCrudColumnConvertionData Convertion { get; set; }

        public Type ConverterType { get; set; }

        public static GenericCrudColumnData BuildFromMetadata(PropertyInfo x)
        {
            GenericCrudColumnData result = new GenericCrudColumnData();
            var attr = x.Attribute<GenericCrudColumnAttribute>();
            result.DisplayAttr = x.Attribute<DisplayAttribute>();
            result.Type = x.PropertyType;
            result.Editable = x.CanWrite;
            result.RenderMode = attr != null ? attr.RenderMode : GenericCrudRenderMode.Any;
            result.Sortable = attr != null ? attr.Sortable : true;
            result.SearchType = attr != null ? attr.SearchType : null;
            result.Name = x.Name;
            result.Required = x.Attribute<RequiredAttribute>() != null;
            if (attr != null)
            {
                result.Convertion = new GenericCrudColumnConvertionData 
                { 
                    NameFrom = x.Name,
                    NameTo = attr.SearchKey ?? x.Name,
                };
            }
            return result;
        }
    }
}